﻿using IShoppingBll;
using IShoppingDal;
using ShoppingEntity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ShoppingBll
{
    public class OrderInfoBll : BaseDeleteBll<OrderInfo>, IOrderInfoBll
    {
        private IOrderInfoDal _orderInfoDal;
        private ICommodityInfoDal _commodityInfoDal;
        private IUserInfoDal _userInfoDal;
        private IDistributionInfoDal _distributionInfoDal;
        private ISalesrRecordDal _salesrRecordDal;
        private ICommodityTypeDal _commodityTypeDal;
        private IUserInfo_RoleInfoDal _userInfo_RoleInfoDal;
        private IRoleInfoDal _roleInfoDal;
        private ShoppingDbContext _dbContext;
        private IReturnExchangeDal _returnExchangeDal;
        private IReturnsDal _returnsDal;

        public OrderInfoBll(IReturnsDal returnsDal,IReturnExchangeDal returnExchangeDal,ShoppingDbContext dbContext,IRoleInfoDal roleInfoDal,IUserInfo_RoleInfoDal userInfo_RoleInfoDal,IOrderInfoDal orderInfoDal, ICommodityInfoDal commodityInfoDal, IUserInfoDal userInfoDal, IDistributionInfoDal distributionInfoDal, ISalesrRecordDal salesrRecordDal , ICommodityTypeDal commodityTypeDal) : base(orderInfoDal)
        {
            _orderInfoDal = orderInfoDal;
            _commodityInfoDal = commodityInfoDal;
            _userInfoDal = userInfoDal;
            _distributionInfoDal = distributionInfoDal;
            _salesrRecordDal = salesrRecordDal;
            _commodityTypeDal = commodityTypeDal;
            _userInfo_RoleInfoDal = userInfo_RoleInfoDal;
            _roleInfoDal = roleInfoDal;
            _dbContext = dbContext;
            _returnExchangeDal = returnExchangeDal;
            _returnsDal = returnsDal;
        }


        /// <summary>
        /// 订单表分页展示、模糊查询
        /// </summary>
        /// <param name="page"></param>
        /// <param name="limit"></param>
        /// <param name="count"></param>
        /// <param name="commodityName"></param>
        /// <returns></returns>
        public object GetOrderInfoPageList(int page, int limit, out int count, string commodityName, UserInfo userInfo)
        {
            var orderInfo = _orderInfoDal.GetEntitiesDb();

            var commodityInfo = _commodityInfoDal.GetEntitiesDb().AsEnumerable();

            if (!string.IsNullOrEmpty(commodityName))
            {
                commodityInfo = _commodityInfoDal.GetEntitiesDb().Where(c => c.CommodityName.Contains(commodityName));
            }

            var Temp = from o in orderInfo
                       join cd in _commodityInfoDal.GetEntitiesDb()
                       on o.GoodsId equals cd.ID into ocTemp
                       from oc in ocTemp.DefaultIfEmpty()

                       join u in _userInfoDal.GetEntitiesDb().Where(u => !u.IsDelete)
                       on o.UserId equals u.ID into ouTemp
                       from ou in ouTemp.DefaultIfEmpty()
                       select new
                       {
                           o.ID,
                           oc.CommodityName,
                           ou.UserName,
                           o.UserId,
                           o.Amount,
                           o.State,
                           o.Num,
                           o.OrderTime
                       };

            var UserRolen = from ur in _userInfo_RoleInfoDal.GetEntitiesDb().Where(u => u.UserId.Contains(userInfo.ID))
                            join r in _roleInfoDal.GetEntitiesDb()
                            on ur.RoleID equals r.ID
                            select new
                            {
                                r.RoleName
                            };


            if (userInfo.UserInfoRole==UserInfo.UserInfoRoleInfoEnum.商家||userInfo.IsAdmin==true)
            {
              
            }else if (userInfo.UserInfoRole == UserInfo.UserInfoRoleInfoEnum.用户)
            {
                Temp = Temp.Where(t => t.UserId.Contains(userInfo.ID));
            }
            else if (userInfo.UserInfoRole == UserInfo.UserInfoRoleInfoEnum.用户)
            {
                Temp = Temp.Where(t => t.State == OrderInfo.OrderStateEnum.已发货);
            }



            //查询出来数据的数量
            count = Temp.Count();
            //分页
            Temp = Temp.OrderBy(c => c.OrderTime).Skip((page - 1) * limit).Take(limit);

            var list = Temp.ToList().Select(c => 
            {
                string State = c.State.ToString();
                return new
                {
                    c.ID,
                    c.CommodityName,
                    c.Num,
                    c.UserName,
                    c.Amount,
                    State,
                    OrderTime = c.OrderTime.ToString("yyyy-MM-dd HH:mm:ss"),
                };

            });

            return list;
        }





        /// <summary>
        /// 配送员接单配送
        /// </summary>
        /// <param name="orderInfo"></param>
        /// <param name="iD"></param>
        /// <returns></returns>
        public bool AddDistributionInfo(string orderInfoId, string UserInfoId)
        {
            OrderInfo orderInfo = _orderInfoDal.GetEntity(orderInfoId);

            UserInfo userInfo = _userInfoDal.GetEntity(orderInfo.UserId);

            DistributionInfo distributionInfo = new DistributionInfo()
            {
                ID = Guid.NewGuid().ToString(),
                OrderID = orderInfo.ID,
                GoodsId = orderInfo.GoodsId,
                UserId = orderInfo.UserId,
                Address = userInfo.Address,
                DistributionId = UserInfoId,
                State = DistributionInfo.DistributionInfoStateEnum.配送中,
                CreateTime = DateTime.Now
            };

            bool isSuccess = _distributionInfoDal.Add(distributionInfo);

            if (isSuccess)
            {
                orderInfo.State = OrderInfo.OrderStateEnum.配送中;
                bool isSuccess2 = _orderInfoDal.Update(orderInfo);
                if (isSuccess2)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                return false;
            }

        }




        /// <summary>
        /// 客户收货方法
        /// </summary>
        /// <param name="orderInfoId"></param>
        /// <returns></returns>
        public bool Goodsreceipt(string orderInfoId)
        {
            var orderInfo = _orderInfoDal.GetEntity(orderInfoId);
            SalesrRecord salesrRecord = new SalesrRecord()
            {
                ID = Guid.NewGuid().ToString(),
                GoodsId = orderInfo.GoodsId,
                Num = orderInfo.Num,
                OrderTime = orderInfo.OrderTime,
                OrderID=orderInfo.ID,
                State=SalesrRecord.SalesrRecordEnum.正常

            };

            bool isSuccess = _salesrRecordDal.Add(salesrRecord);
            if (isSuccess)
            {

                orderInfo.State = OrderInfo.OrderStateEnum.订单已完成;
                orderInfo.EndTime = DateTime.Now;
                bool isSuccess2 = _orderInfoDal.Update(orderInfo);

                if (isSuccess2)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            else
            {
                return false;
            }
        }


        /// <summary>
        /// 退货
        /// </summary>
        /// <param name="orderInfoId"></param>
        /// <returns></returns>
        public bool Salesreturn(string orderInfoId,out string msg)
        {
            msg = "";
            OrderInfo orderInfo = _orderInfoDal.GetEntity(orderInfoId);
            if (orderInfo.EndTime == null)
            {
                msg = "可退货";
                return true;
            }
            else
            {
                DateTime beginTime = Convert.ToDateTime(orderInfo.EndTime);
                DateTime PresentTime = DateTime.Now;
                int days = (PresentTime - beginTime).Days;
                if (days > 7)
                {
                    msg = "您的商品以超过退货期限";
                    return false;
                }
                else
                {
                    msg = "可退货";
                    return true;
                }
            }
        }



        /// <summary>
        /// 获取退货商品的数据
        /// </summary>
        /// <param name="orderInfoId"></param>
        /// <returns></returns>
        public object AddSalesreturnViewOption(string orderInfoId)
        {
            var Temp = from o in _orderInfoDal.GetEntitiesDb().Where(s => s.ID.Contains(orderInfoId))
                       join cd in _commodityInfoDal.GetEntitiesDb()
                       on o.GoodsId equals cd.ID into ccTemp
                       from cc in ccTemp.DefaultIfEmpty()

                       join ct in _commodityTypeDal.GetEntitiesDb()
                       on cc.CategoryId equals ct.ID into ctTemp
                       from cct in ctTemp.DefaultIfEmpty()
                       select new
                       {
                           o.ID,
                           cc.CommodityName,
                           cct.CategoryName,
                       };
            return Temp;
        }



        /// <summary>
        /// 退货申请，添加退货记录
        /// </summary>
        /// <param name="orderId"></param>
        /// <param name="reason"></param>
        /// <returns></returns>
        public bool AddSalesreturn(string orderId, string reason)
        {
            OrderInfo orderInfo = _orderInfoDal.GetEntity(orderId);

            using (var transaction = _dbContext.Database.BeginTransaction())
            {
                ReturnExchange returnExchange = new ReturnExchange()
                {
                    ID = Guid.NewGuid().ToString(),
                    OrderId = orderInfo.ID,
                    GoodsId = orderInfo.GoodsId,
                    UserId = orderInfo.UserId,
                    Reason = reason,
                    State = ReturnExchangeStatusEnum.待商家审批,
                    CreateTime = DateTime.Now,
                    IsDelete=false
                };
                bool isSuccess1 = _returnExchangeDal.Add(returnExchange);
                orderInfo.State = OrderInfo.OrderStateEnum.退货申请;
                bool isSuccess2 = _orderInfoDal.Update(orderInfo);
                if (isSuccess1 && isSuccess2)
                {
                    transaction.Commit();
                    return true;
                }
                else
                {
                    transaction.Rollback();
                    return false;
                }
                

            }

        }

        /// <summary>
        /// 退回货物
        /// </summary>
        /// <param name="orderId"></param>
        /// <returns></returns>
        public bool Turndestock(string orderId)
        {
            using (var transaction = _dbContext.Database.BeginTransaction())
            {

                OrderInfo orderInfo = _orderInfoDal.GetEntity(orderId);
                orderInfo.State = OrderInfo.OrderStateEnum.货物待揽收;
                Returns returns = new Returns()
                {
                    ID = Guid.NewGuid().ToString(),
                    GoodsId = orderInfo.GoodsId,
                    UserId = orderInfo.UserId,
                    OrderId=orderInfo.ID,
                    State = Returns.ReturnsStateEnum.待揽收,
                    Address = "仓库",
                    CreateTime = DateTime.Now
                };
                bool isSuccess1 = _orderInfoDal.Update(orderInfo);
                bool isSuccess2 = _returnsDal.Add(returns);
                if (isSuccess1 && isSuccess2)
                {
                    transaction.Commit();
                    return true;
                }
                else
                {
                    transaction.Rollback();
                    return false;
                }
            }

        }


        public bool Refund(string orderInfoId)
        {
            using (var transaction=_dbContext.Database.BeginTransaction())
            {
                //修改订单信息
                OrderInfo orderInfo = _orderInfoDal.GetEntity(orderInfoId);
                orderInfo.State = OrderInfo.OrderStateEnum.退款完成;
                bool isSuccess1 = _orderInfoDal.Update(orderInfo);

                //退款给客户
                UserInfo userInfo = _userInfoDal.GetEntity(orderInfo.UserId);
                userInfo.Balance += orderInfo.Amount;
                bool isSuccess2 = _userInfoDal.Update(userInfo);

                //修改销售记录
                SalesrRecord salesrRecord = _salesrRecordDal.GetEntitiesDb().Where(s => s.OrderID.Contains(orderInfo.ID)).FirstOrDefault();
                salesrRecord.State = SalesrRecord.SalesrRecordEnum.退款;
                bool isSuccess3 = _salesrRecordDal.Update(salesrRecord);

                if (isSuccess1 && isSuccess2 && isSuccess3)
                {
                    transaction.Commit();
                    return true;
                }
                else
                {
                    transaction.Rollback();
                    return false;
                }
                
            }
        }



    }
}
